package com.mall.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.common.R;
import com.mall.common.SameSiteCookie;
import com.mall.entity.LoginUser;
import com.mall.entity.SmoothMallCategory;
import com.mall.entity.SmoothMallUser;
import com.mall.service.SmoothMallUserService;
import lombok.val;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class SmoothMallUserController {
    @Autowired
    SmoothMallUserService smoothMallUserService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    PasswordEncoder passwordEncoder;
    @PostMapping("/register")
    public R register(@RequestBody SmoothMallUser smoothMallUser){
        if (smoothMallUser.getPassword()==null||smoothMallUser.getPassword()==null){
            return R.error("用户名和密码不能为空");
        }
        SmoothMallUser mallUser = smoothMallUserService.getOne(new LambdaQueryWrapper<SmoothMallUser>()
                .eq(SmoothMallUser::getUsername, smoothMallUser.getUsername()));
        if (mallUser!=null){
            return R.error("该用户名已经被注册过了");
        }
        smoothMallUser.setPersonalizedSignature("只喝冰过的饮料");
        String password = passwordEncoder.encode(smoothMallUser.getPassword());
        smoothMallUser.setPassword(password);
        smoothMallUser.setRole(1);
        smoothMallUser.setCreateTime(LocalDateTime.now());
        smoothMallUserService.save(smoothMallUser);
        return R.success(smoothMallUser);
    }
    @PostMapping("/login")
    public R login(@RequestBody SmoothMallUser smoothMallUser, HttpSession session, HttpServletResponse response){
        HashMap<String, String> map = smoothMallUserService.login(smoothMallUser);
        if (StringUtils.isEmpty(map.get("token"))){
            return R.error("error");
        }
//        session.setAttribute("token",map.get("token"));
        SameSiteCookie cookie = new SameSiteCookie("sessionId", map.get("token")); // 将 sessionId 添加到 Cookie 中
        cookie.setMaxAge(180); // 设置 Cookie 的过期时间，单位为秒。此处设置30秒;
        cookie.setPath("/");
        cookie.setSecure(true);
        cookie.setHttpOnly(true);
        cookie.setDomain(""); // 或者省略这一行
        cookie.setSameSite("None"); // 设置 SameSite 属性为 "None"
        response.addCookie(cookie); // 将 Cookie 添加到 HTTP Response 中
        return R.success(map);
    }
    @GetMapping("/token")
    public String getToken(HttpSession session){
        String token = (String) session.getAttribute("token");
        return token;
    }
    @PostMapping("/update/{signature}")
    public R update(@PathVariable String signature,HttpSession session){
        SmoothMallUser user = (SmoothMallUser) session.getAttribute("user");
        if (user==null){
            return R.error("该账号未登录请先登录");
        }
        SmoothMallUser mallUser = smoothMallUserService.getOne(new LambdaQueryWrapper<SmoothMallUser>()
                .eq(SmoothMallUser::getUsername, user.getUsername()));
        mallUser.setPersonalizedSignature(signature);
        boolean b = smoothMallUserService.updateById(user);
        if (b){
            return R.success("更新成功");
        }
        return R.error("更新失败");
    }
    @GetMapping("/logout")
    public R logout(HttpServletRequest request,HttpSession session,HttpServletResponse response){
        //根据在JWT已经解析的token并存放在上下文的Auth对象获取id删除缓存
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getPrincipal()==null){
            return R.error("失败");
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getSmoothMallUser().getId();
        Boolean aBoolean = redisTemplate.delete("token:" + userid);
        SecurityContextHolder.clearContext();//清除上下文信息
        // 清除Cookie中的token
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("sessionId")) { // session对应的cookie名
                    cookie.setMaxAge(0); // 设置过期
                    cookie.setValue(null); // 删除Cookie中的值
                    cookie.setPath("/"); // 根路径，与存入时路径相同
                    response.addCookie(cookie); // 反回至客户端
                    break;
                }
            }
        }
        if (aBoolean){
            return R.success("退出登录成功");
        }else {
            return R.error("退出登录失败");
        }

    }
    @PostMapping("/adminLogin")
    public R adminLogin(@RequestBody SmoothMallUser smoothMallUser){
        String username = smoothMallUser.getUsername();
        SmoothMallUser mallUser = smoothMallUserService.getOne(new LambdaQueryWrapper<SmoothMallUser>().eq(SmoothMallUser::getUsername, username));
        if (mallUser==null){
            return R.error("该管理员不存在");
        }
        if (mallUser.getRole()!=2){
            return R.error("你没有管理员权限，请返回用户登录");
        }
        if (!mallUser.getPassword()
                .equals(DigestUtils.md5DigestAsHex(smoothMallUser.getPassword().getBytes())
                )){
            return R.error("密码输入错误");
        }
        return R.success(mallUser);
    }
}
